﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BitTorrentSharp.Peers
{
	/// <summary>
	/// Represent as a message that contains piece data send to a peer.
	/// </summary>
	public class PieceMessage : PeerNonKeepAliveMessage
	{
		/// <summary>
		/// Get or set the index of the piece in peice set.
		/// </summary>
		public int Index
		{
			get;
			set;
		}

		/// <summary>
		/// Get or set the begin position of the data in bytes.
		/// </summary>
		public int Begin
		{
			get;
			set;
		}

		/// <summary>
		/// Get or set the data stream of the piece.
		/// </summary>
		public byte[] Data
		{
			get;
			set;
		}

		/// <summary>
		/// Get the type of the message. This property always returns <see cref="PeerMessageType.Piece"/>.
		/// </summary>
		public override PeerMessageType Type
		{
			get
			{
				return PeerMessageType.Piece;
			}
		}

		/// <summary>
		/// Get the data sequence of this message.
		/// </summary>
		/// <returns>The data sequence of this message.</returns>
		protected override byte[] GetPayloadBytes()
		{
			return ByteHelper.Concat(BitConverter.GetBytes(Index).EnsureBigEndian(), BitConverter.GetBytes(Begin).EnsureBigEndian(), this.Data);
		}


		/// <summary>
		/// Initialize a new instance of the message.
		/// </summary>
		/// <param name="index">The index of the piece in peice set.</param>
		/// <param name="begin">The begin position of the data in bytes.</param>
		/// <param name="data">The data sequence in this message.</param>
		public PieceMessage(int index, int begin, byte[] data)
		{
			if (data == null)
			{
				throw new ArgumentNullException("data");
			}

			this.Index = index;
			this.Begin = begin;
			this.Data = data;
		}
	}
}
